<template>
  <div class="app-container">
    <div class="container-left">
      <div>
        <el-button
          type="primary"
          @click="addSearch(0, '查询任务', '查询任务', '', '', '查询任务')"
          >新建查询任务</el-button
        >
        <div class="title">任务列表管理</div>
        <div>
          <el-tree
            :data="leftMenu"
            :props="defaultProps"
            @node-click="handleClickLeftMenu"
            node-key="id"
            :default-expanded-keys="defaultValues"
            :current-node-key="currentNodeKey"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <div :class="data.id ? 'isCanmpany ' : 'noAc '">
                {{ data | nameFilter }}

                {{ data.child ? `(${data.child.length})` : "" }}
              </div>
            </div>
          </el-tree>
        </div>
      </div>
      <div
        class="history-it"
        @click="addSearch(2, '历史查询', '历史查询', '', '', '历史查询')"
      >
        历史记录（{{ historyTotal }}）
      </div>
    </div>
    <div class="container-right">
      <div class="container-right-menu">
        <el-tabs
          class="lll"
          v-model="jobActiveObj.id"
          type="card"
          closable
          @tab-remove="removeTab"
          @tab-click="tabClick"
        >
          <el-tab-pane
            style="margin-right: 10px"
            class="tab-it"
            :key="item.id"
            v-for="(item, index) in jobList"
            :label="
              item.queryStatus == 100 || item.queryStatus == 300
                ? item.phone
                : item.name
            "
            :name="item.id"
          >
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- {{ jobActiveObj.status }} -->
      <div :class="jobActiveObj.jobActive == '查询任务' ? 'loginbg' : ''">
        <img
          v-if="jobActiveObj.jobActive == '查询任务'"
          src="../../assets/images/loginbg.jpg"
        />
        <keep-alive>
          <login
            class="login-style"
            @loginIn="loginIn"
            @initMenu="initLeftMenu"
            v-if="jobActiveObj.jobActive == '查询任务'"
          ></login>
        </keep-alive>

        <tabebleData
          ref="tableRef"
          :jobActive="jobActiveObj.jobActive"
          :jobActiveObj="jobActiveObj"
          :leftMenu="leftMenu"
          @goOut="goOut"
          @editData="editData"
          v-if="
            jobActiveObj.jobActive != '查询任务' &&
              jobActiveObj.jobActive != '' &&
              jobActiveObj.jobActive != '历史查询'
          "
        ></tabebleData>
        <keep-alive>
          <historyList
            @seedetail="seedetail"
            v-if="jobActiveObj.jobActive == '历史查询'"
          ></historyList>
        </keep-alive>
      </div>
    </div>
  </div>
</template>

<script>
import tabebleData from "./components/tabebleData.vue";
import login from "./components/login.vue";
import historyList from "./components/historyList.vue";
import { getAllStatusTask } from "@/api/tax";
import { setJob, getJob } from "@/utils/auth";
export default {
  components: {
    tabebleData,
    login,
    historyList
  },
  watch: {
    "jobActiveObj.jobActive": {
      handler(newVal, oldVal) {
        this.jobActiveObj.jobActive = newVal;
      },
      deep: true
    },
    "jobActiveObj.status": {
      handler(newVal, oldVal) {
        // this.jobActiveObj.jobActive = newVal;
      },
      deep: true
    }
  },
  filters: {
    nameFilter(data) {
      if (data.id) {
        if (data.queryStatus == 100 || data.queryStatus == 300) {
          return data.phone;
        } else {
          return data.enterpriseName;
        }
      } else {
        return data.name;
      }
    }
  },
  data() {
    return {
      timerId: null, // 用于存储定时器的ID
      defaultValues: [],
      currentNodeKey: null,
      jobActiveObj: {
        jobActive: "",
        id: "",
        status: null,
        enterpriseName: "",
        registerAddress: ""
      },

      defaultProps: {
        label: "name",
        children: "child"
      },
      leftMenu: [
        //左侧菜单
        { name: "进行中", num: 0, type: 0, child: [] },
        { name: "已完成", num: 0, type: 1, child: [] },
        { name: "查询失败", num: 0, type: 2, child: [] }
      ],
      jobList: [], //顶部菜单
      historyTotal: 0
    };
  },
  created() {
    setTimeout(async () => {
      await this.initLeftMenu();

      // this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
      // 缓存tab代码
      if (this.leftMenu.every(v => v.child.length === 0)) {
        const jobList = getJob("jobList") || [];
        if (jobList.length > 0) {
          const jobActiveObj1 = getJob("jobActive") || {
            jobActive: "",
            id: "",
            status: null,
            enterpriseName: "",
            registerAddress: ""
          };
          //遍历本地 保存jobList
          jobList.forEach(v => {
            this.addSearch(v.type, v.name, v.name, "", "", v.name);
          });
          this.jobActiveObj = jobActiveObj1;
        } else {
          this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
        }
      } else {
        //取本地的值
        if (getJob("jobList") && getJob("jobActive")) {
          this.jobList = getJob("jobList");
          this.jobActiveObj = getJob("jobActive");
        } else {
          this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
        }
      }
    }, 0);
    let timer = setInterval(() => {
      this.initLeftMenu();
    }, 5000);

    this.$once("hook:beforeDestroy", () => {
      clearInterval(timer);
      timer = null;
    });
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器
    clearInterval(this.timerId);
  },
  methods: {
    //退出
    goOut(e) {
      if (e.type == 0) {
        this.removeTab(e.id);
      } else {
        this.removeTab(e.id);
        this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
      }
    },
    //历史查询
    seedetail(v) {
      // this.removeTab('历史记录', 2)
      this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
    },
    // 统一处理状态
    datafun() {
      setTimeout(() => {
        const t1 = this.leftMenu[1].child.some(v => {
          return v.id == this.jobActiveObj.id;
        });
        const t2 = this.leftMenu[2].child.some(v => {
          return v.id == this.jobActiveObj.id;
        });
        const t3 = this.leftMenu[0].child.some(v => {
          return v.id == this.jobActiveObj.id;
        });
        if (t1) {
          this.editData({
            id: this.jobActiveObj.id,
            status: 200,
            jobActive: this.jobActiveObj.jobActive
          });
        }
        if (t2) {
          this.editData({
            id: this.jobActiveObj.id,
            status: 300,
            jobActive: this.jobActiveObj.jobActive
          });
        }
        if (t3) {
          this.editData({
            id: this.jobActiveObj.id,
            status: 100,
            jobActive: this.jobActiveObj.jobActive
          });
        }
      }, 500);
    },
    // 修改状态
    editData(e) {
      const mapObj = {
        100: 0,
        200: 1,
        300: 2
      };
      const idx = this.leftMenu[mapObj[e.status]].child.findIndex(v => {
        return v.id == e.id;
      });

      const jList = JSON.parse(JSON.stringify(this.jobList));
      jList.forEach(v => {
        if (v.id == e.id) {
          v.name = this.leftMenu[mapObj[e.status]].child[idx].enterpriseName;
          v.queryStatus = e.status;
        }
      });
      this.jobList = jList;

      this.jobActiveObj = {
        jobActive: e.jobActive,
        id: typeof e.id == "string" ? e.id : e.id + "",
        status: e.status,
        enterpriseName: this.leftMenu[mapObj[e.status]].child[idx]
          .enterpriseName,
        registerAddress: this.leftMenu[mapObj[e.status]].child[idx]
          .registerAddress
      };
      this.defaultValues = [e.id];
      this.currentNodeKey = e.id;
      setJob(this.jobActiveObj, this.jobList);
    },
    //登录回调
    loginIn(e) {
      console.log(e, "eeee");
      this.initLeftMenu();
      if (e.enterpriseId) {
        //type, name, enterpriseId, queryStatus, phone, id
        this.addSearch(
          e.type,
          e.name,
          e.enterpriseId,
          e.queryStatus,
          e.phone,
          e.id
        );
        this.jobActiveObj.jobActive =
          typeof e.enterpriseId == "string"
            ? e.enterpriseId
            : e.enterpriseId + "";
        this.jobActiveObj.id = e.id;
        this.defaultValues = [e.id];
      }
      // setTimeout(()=> {

      // },3000)
    },

    // 切换
    tabClick(e) {
      // return
      this.initLeftMenu();
      this.jobActiveObj.id = e.name;
      let idx = this.jobList.findIndex(v => {
        return v.id == e.name;
      });
      // return

      this.datafun();
      this.jobActiveObj.jobActive = this.jobList[idx].enterpriseId;
      this.jobActiveObj.status = this.jobList[idx].queryStatus;
      this.jobActiveObj.enterpriseName = this.jobList[idx].name;
      this.jobActiveObj.registerAddress = this.jobList[idx].registerAddress;
      if (idx != 0) {
        this.$nextTick(() => {
          this.$refs.tableRef.editNmae();
        });
      }
      setJob(this.jobActiveObj, this.jobList);
    },
    // 删除tabs
    removeTab(e, type = 0) {
      const idx = this.jobList.findIndex(v => {
        return v.id == e;
      });

      if (idx == 0 && idx == this.jobList.length - 1) {
        this.jobList.splice(idx, 1);
        if (type == 0) {
          return this.addSearch(0, "查询任务", "查询任务", "", "", "查询任务");
        }
      }

      if (idx == 0 && idx != this.jobList.length - 1) {
        this.jobActiveObj.jobActive = this.jobList[idx + 1].enterpriseId;
        this.jobActiveObj.id = this.jobList[idx + 1].id;
        this.jobActiveObj.status = this.jobList[idx + 1].queryStatus;
        this.jobActiveObj.enterpriseName = this.jobList[idx + 1].name;
        this.jobActiveObj.registerAddress = this.jobList[
          idx + 1
        ].registerAddress;
      }
      if (idx == this.jobList.length - 1) {
        this.jobActiveObj.jobActive = this.jobList[idx - 1].enterpriseId;
        this.jobActiveObj.id = this.jobList[idx - 1].id;
        this.jobActiveObj.status = this.jobList[idx - 1].queryStatus;
        this.jobActiveObj.enterpriseName = this.jobList[idx - 1].name;
        this.jobActiveObj.registerAddress = this.jobList[
          idx - 1
        ].registerAddress;
      }
      if (idx < this.jobList.length - 1) {
        this.jobActiveObj.jobActive = this.jobList[idx + 1].enterpriseId;
        this.jobActiveObj.id = this.jobList[idx + 1].id;
        this.jobActiveObj.status = this.jobList[idx + 1].queryStatus;
        this.jobActiveObj.registerAddress = this.jobList[
          idx + 1
        ].registerAddress;
      }
      // this.editData(this.jobActiveObj)
      this.jobList.splice(idx, 1);
      setJob(this.jobActiveObj, this.jobList);
    },
    //add tabs
    addSearch(
      type,
      name,
      enterpriseId,
      queryStatus,
      phone,
      id,
      registerAddress
    ) {
      this.jobActiveObj = {
        jobActive: "",
        id: "",
        status: null,
        enterpriseName: "",
        registerAddress: ""
      };
      this.jobActiveObj.jobActive =
        typeof enterpriseId == "string" ? enterpriseId : enterpriseId + "";
      this.jobActiveObj.id = typeof id == "string" ? id : id + "";
      this.$set(this.jobActiveObj, "status", queryStatus);
      this.jobActiveObj.enterpriseName = name;
      this.jobActiveObj.registerAddress = registerAddress;
      const t = this.jobList.some(v => {
        return v.id == id;
      });
      let jList = JSON.parse(JSON.stringify(this.jobList));
      if (!t) {
        jList.push({
          name,
          type,
          enterpriseId,
          queryStatus,
          phone,
          id: String(id),
          registerAddress: registerAddress
        });
      } else {
      }
      this.jobList = jList;
      setJob(this.jobActiveObj, this.jobList);
      this.datafun();

      // this.initLeftMenu();
    },
    handleClickLeftMenu(v) {
      if (v.enterpriseId) {
        // return
        this.addSearch(
          1, // 类型
          v.enterpriseName || "", //公司名称
          typeof v.enterpriseId == "string"
            ? v.enterpriseId
            : v.enterpriseId + "", // 处理企业ID
          v.queryStatus, // 数据状态
          v.phone, // 手机号
          v.id, // 数据ID
          v.registerAddress
        );
        this.$nextTick(() => {
          this.$refs.tableRef.editNmae();
        });
      }
    },
    // 初始化菜单
    async initLeftMenu() {
      const res = await getAllStatusTask();
      this.historyTotal = res.data.history;
      const mList = res.data;
      let menuMaping = {
        0: "inProgress",
        1: "finish",
        2: "fail"
      };

      this.leftMenu.forEach(v => {
        v.child = mList[menuMaping[v.type]] || [];
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-tabs--card > .el-tabs__header .el-tabs__item.is-closable:hover {
  padding-left: 10px;
  padding-right: 10px;
}
/deep/ .el-card {
  border: none;
}
.lll {
  /deep/ .el-tab-pane {
    background-color: #f0f0f0; /* 设置背景颜色 */
    border-bottom-color: #fff;
    color: #333; /* 设置文本颜色 */
  }
  /deep/ .el-tabs__item.is-active {
    color: #333;
    background-color: #e5e5e5 !important;
    border-bottom-color: #e5e5e5;
  }
  /deep/ .el-tabs__item:hover {
    color: #333;
    // background-color: #e5e5e5 !important;
  }
}

.history-it {
  padding: 8px 24px;
  cursor: pointer;
  color: #606266;
}
.history-it:hover {
  background: #f5f5f6;
}
/deep/ .el-tree-node__content {
  height: 36px;
}

.loginbg {
  position: relative;
  img {
    width: 100%;
    height: calc(100vh - 110px);
  }

  // background-repeat: no-repeat; /* 取消重复 */
  // background-position: center; /* 居中显示 */
  // background-size: cover; /* 铺满 */
  // background-image: url("../../assets/images/loginbg.png");
  .login-style {
    width: 500px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
/deep/ .el-tabs__header {
  border: none;
  // width: 100vw;
  // background-color: #fff !important;
}
/deep/ .el-tabs__item {
  // margin-right: 5px;
}
.app-container {
  display: flex;
  background-color: #f5f5f5;
  .container-left {
    width: 300px;
    height: calc(100vh - 70px);

    padding: 10px;
    background-color: #fff;
    margin-right: 20px;

    .title {
      margin: 20px 0;
    }
    .isCanmpany {
      width: 180px;
      font-size: 14px;
      white-space: nowrap; //不换行
      overflow: hidden; //超出部分隐藏
      text-overflow: ellipsis; //文本溢出显示省略号
    }
    .noAc {
    }
  }
  .container-right {
    width: 100%;
    overflow: hidden;

    .container-right-menu {
      padding: 0 5px;
      height: 44px;
      // position: fixed;
      // font-size: 0px;
      // top: 0;
      // bottom: 0;
      // left: 0;
      // z-index: 1001;
      // overflow: hidden;
      /deep/ .el-tabs--card > .el-tabs__header .el-tabs__nav {
        border: none;
      }
      /deep/ .el-tabs--card > .el-tabs__header .el-tabs__item {
        border-left: none;
      }
      /deep/ .el-tabs__item {
        margin-right: 10px;
        width: 150px;
        position: relative;
        // color: #222;
        // border: 1px solid #ddd;
        // border-bottom-color: #FFF;
        border-radius: 8px 8px 0px 0px;
        background-color: #fff;
        white-space: nowrap; //不换行
        overflow: hidden; //超出部分隐藏
        text-overflow: ellipsis; //文本溢出显示省略号
        .is-active {
          //  color: pink !important;
        }
        > span {
          position: absolute;
          right: 5px;
          top: 50%;
          transform: translate(0, -50%);
        }
      }
    }
  }
}

/deep/ .el-tabs__item:focus.is-active.is-focus:not(:active) {
  box-shadow: none !important;
}

.tab-it {
  margin-right: 10px;
}
</style>
